package app.qrcode.browser.todoapp.data.viewmodel

import android.app.Application
import androidx.lifecycle.*
import app.qrcode.browser.todoapp.App.Companion.appContext
import app.qrcode.browser.todoapp.data.ToDoDataBase
import app.qrcode.browser.todoapp.data.models.TaskStatus
import app.qrcode.browser.todoapp.data.models.ToDoData
import app.qrcode.browser.todoapp.data.repository.ToDoRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Created by YiGo on 2022/5/6.
 */
class ToDoViewModel : ViewModel() {
    private val toDoDao = ToDoDataBase.getDataBase(appContext).toDoDao()
    private val repository: ToDoRepository = ToDoRepository(toDoDao)
    val getAllData: LiveData<List<ToDoData>> = repository.getAllData
    val sortByHighPriority: LiveData<List<ToDoData>> = repository.sortByHighPriority
    val sortByLowPriority: LiveData<List<ToDoData>> = repository.sortByLowPriority
    val sortByHighTaskStatus: LiveData<List<ToDoData>> = repository.sortByHighTaskStatus
    val sortByLowTaskStatus: LiveData<List<ToDoData>> = repository.sortByLowTaskStatus
    val classifiedIntoHighPriority: LiveData<List<ToDoData>> = repository.classifiedIntoHighPriority
    val classifiedIntoMediumPriority: LiveData<List<ToDoData>> =
        repository.classifiedIntoMediumPriority
    val classifiedIntoLowPriority: LiveData<List<ToDoData>> = repository.classifiedIntoLowPriority
    val classifiedIntoHighTaskStatus: LiveData<List<ToDoData>> =
        repository.classifiedIntoHighTaskStatus
    val classifiedIntoMediumTaskStatus: LiveData<List<ToDoData>> =
        repository.classifiedIntoMediumTaskStatus
    val classifiedIntoLowTaskStatus: LiveData<List<ToDoData>> =
        repository.classifiedIntoLowTaskStatus

//    val currentDate: MutableLiveData<String> by lazy {
//        MutableLiveData<String>()
//    }
//
//    val currentTime: MutableLiveData<String> by lazy {
//        MutableLiveData<String>()
//    }

    fun insertData(toDoData: ToDoData) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.insertData(toDoData)
        }
    }

    fun updateData(toDoData: ToDoData) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.updateData(toDoData)
        }
    }

    fun updateTaskStatus(id: Int, taskStatus: TaskStatus) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.updateTaskStatus(id, taskStatus)
        }
    }

    fun deleteItem(toDoData: ToDoData) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.deleteItem(toDoData)
        }
    }

    fun deleteAll() {
        viewModelScope.launch(Dispatchers.IO) {
            repository.deleteAll()
        }
    }

    fun searchDatabase(searchQuery: String): LiveData<List<ToDoData>> {
        return repository.searchDatabase(searchQuery)
    }
}